﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace Forest.Cat.Domain.Shared.Validation
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public class DateTimeValidationAttribute : ValidationAttribute
    {
        public DateTimeValidationAttribute()
        { }

        /// <summary>
        /// 重写验证方法
        /// </summary>
        /// <param name="value"></param>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime time = DateTime.Now;

            // 通过验证
            if (string.IsNullOrWhiteSpace(Convert.ToString(value)) || DateTime.TryParse(value.ToString(), out time))
            {
                return ValidationResult.Success;
            }

            var validationResult = new ValidationResult("日期格式不正确!",
                new string[] { validationContext.MemberName });

            return validationResult;
        }
    }
}
